package com.test.nnooolwdeaer.activity_fragment_wooden.info_wooden;

import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.google.gson.JsonArray;
import com.test.nnooolwdeaer.R;
import com.test.nnooolwdeaer.activity_fragment_wooden.base_wooden.BaseInfoActivity_wooden;
import com.test.nnooolwdeaer.bean_wooden.StaticVariate_wooden;
import com.test.nnooolwdeaer.bean_wooden.process_wooden.ProcessData_wooden;
import com.test.nnooolwdeaer.bean_wooden.process_wooden.ProcessInfo_wooden;
import com.test.nnooolwdeaer.bean_wooden.process_wooden.ProcessStep_wooden;
import com.test.nnooolwdeaer.constant_wooden.Constant_wooden;
import com.test.nnooolwdeaer.util_wooden.StringUtil_wooden;
import com.test.nnooolwdeaer.util_wooden.http_wooden.HttpManager_wooden;
import com.test.nnooolwdeaer.view_wooden.base_wooden.BaseInfoInputViewManager_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.AddressPickViewManager_Niri_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.AddressPickViewManager_Viet_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.ContactViewManager_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.CreditReportViewManager_Niri_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.DatePickViewManager_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.GenderSelectViewManager_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.InputViewManager_wooden;
import com.test.nnooolwdeaer.view_wooden.info_input_wooden.SelectViewManager_wooden;
import com.test.nnooolwdeaer.view_wooden.widget_wooden.TitleView_wooden;

import java.util.ArrayList;
import java.util.TreeMap;

public class InfoUploadActivity_wooden extends BaseInfoActivity_wooden {

    private LinearLayout groupLayout_wooden;

    private final ArrayList<BaseInfoInputViewManager_wooden> infoInputViewManagers_wooden = new ArrayList<>();

    private ProcessStep_wooden step_wooden;

    private String buriedPointFalg_wooden = "";
    private String activityFlag_wooden = "";

    //尼日银行选择
    private String paramNameBankCode_wooden = "";
    private ProcessData_wooden bankNameData_wooden;
    private final TreeMap<String,String> map_bankName_bankCode_wooden = new TreeMap<>();

    private int contactIndex = -1;

    private final ActivityResultLauncher<Intent> contactLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                try {
                    Intent data = result.getData();
                    if (data!=null && result.getResultCode()==RESULT_OK){
                        Uri contactUri = data.getData();
                        String[] queryFields = new String[]{
                                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                                ContactsContract.CommonDataKinds.Phone.NUMBER
                        };
                        Cursor cursor = getContentResolver().query(contactUri,queryFields,null,null,null);
                        if (cursor!=null){
                            if (cursor.moveToFirst()){
                                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                                @SuppressLint("Range") String mobile = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                                if (contactIndex>=0 && contactIndex<infoInputViewManagers_wooden.size()){
                                    BaseInfoInputViewManager_wooden infoInputViewManager = infoInputViewManagers_wooden.get(contactIndex);
                                    if (infoInputViewManager instanceof ContactViewManager_wooden){
                                        ContactViewManager_wooden contactViewManager = (ContactViewManager_wooden) infoInputViewManager;
                                        contactViewManager.contactSet(name,mobile);
                                    }
                                    contactIndex = -1;
                                }
                            }
                            cursor.close();
                        }
                    }
                }catch (Exception e){
                    if (Constant_wooden.Debug) e.printStackTrace();
                }
            }
    );


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_upload_wooden);
        init_wooden();
    }

    @SuppressLint("InflateParams")
    private void init_wooden(){
        TitleView_wooden titleView = findViewById(R.id.activity_info_upload_view_title);
        setBackBtn_wooden(titleView.getBackIb_wooden());

        groupLayout_wooden = findViewById(R.id.activity_info_upload_layout_group);

        View tipsView = findViewById(R.id.activity_info_upload_view_tips);
        TextView tipsTv = findViewById(R.id.activity_info_upload_tv_tips);

        findViewById(R.id.activity_info_upload_btn_next).setOnClickListener(v -> {

            titleView.requestFocus();

            for (BaseInfoInputViewManager_wooden widgetsManager: infoInputViewManagers_wooden){
                if (!widgetsManager.checkInput_wooden()){
                    showToast_wooden(getString(R.string.word_input_tip));
                    return;
                }
            }
            HttpManager_wooden.getInstance_wooden().saveUserBuriedPointAndUpload((buriedPointFalg_wooden + "_CLICK").toUpperCase());
            if (step_wooden ==null) return;
            String url = step_wooden.getApiUrl_wooden();
            if (url.isEmpty()) return;
            TreeMap<String,String> dataMap = new TreeMap<>();

            JsonArray contactArray = new JsonArray();

            for (BaseInfoInputViewManager_wooden baseInfoInputViewManager: infoInputViewManagers_wooden){

                ProcessData_wooden data = baseInfoInputViewManager.getData_wooden();

                if (baseInfoInputViewManager instanceof ContactViewManager_wooden){
                    //添加联系人信息
                    if (!TextUtils.isEmpty(step_wooden.getContactParamName_wooden())){
                        contactArray.add(((ContactViewManager_wooden) baseInfoInputViewManager).getContactJson());
                    }

                }else {
                    if (data==null) continue;
                    switch (data.getAction_wooden()) {
                        case Constant_wooden.Data_Action_Address_Pick_wooden -> {//地址联动模块
                            //尼日
                            if (StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Nigeria_wooden)) {
                                if (!(baseInfoInputViewManager instanceof AddressPickViewManager_Niri_wooden))
                                    continue;
                                AddressPickViewManager_Niri_wooden addressPickViewManager = (AddressPickViewManager_Niri_wooden) baseInfoInputViewManager;
                                dataMap.put(data.getParamNameState_wooden(), addressPickViewManager.getState_wooden());
                                dataMap.put(data.getParamNameCity_wooden(), addressPickViewManager.getCity_wooden());
                                dataMap.put(data.getParamNameArea_wooden(), addressPickViewManager.getArea_wooden());
                            }
                            //越南
                            if (StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Vietnam_wooden)) {
                                if (!(baseInfoInputViewManager instanceof AddressPickViewManager_Viet_wooden))
                                    continue;
                                AddressPickViewManager_Viet_wooden addressPickViewManager = (AddressPickViewManager_Viet_wooden) baseInfoInputViewManager;
                                dataMap.put(data.getParamName_wooden(), addressPickViewManager.getState_wooden());
                                dataMap.put(data.getParamNameCity_wooden(), addressPickViewManager.getCity_wooden());
                            }
                        }
                        case Constant_wooden.Data_Action_Bank_Pick_wooden -> {//尼日银行选择模块
                            String bankName = ((SelectViewManager_wooden) baseInfoInputViewManager).getTextInput_wooden();
                            String bankCode = map_bankName_bankCode_wooden.get(bankName);
                            dataMap.put(data.getParamNameBankName_wooden(), bankName);
                            dataMap.put(data.getParamNameBankCode_wooden(), bankCode);
                        }
                        default ->
                                dataMap.put(data.getParamName_wooden(), baseInfoInputViewManager.getInput_wooden());
                    }
                }

            }

            if (!contactArray.isEmpty())
                dataMap.put(step_wooden.getContactParamName_wooden(),contactArray.toString());

            HttpManager_wooden.getInstance_wooden().uploadInfo_wooden(url,dataMap);
        });

        step_wooden = ProcessInfo_wooden.getInstance_wooden().getStep_wooden(0);
        String stepName = ProcessInfo_wooden.getInstance_wooden().getStepName_wooden(0);
        buriedPointFalg_wooden = stepName;
        switch (buriedPointFalg_wooden) {
            case "personal_info" -> {
                activityFlag_wooden = "BASIC";
                titleView.setVisibility(VISIBLE);
                tipsView.setVisibility(VISIBLE);
                tipsTv.setText(getText(R.string.process_tips_personal));
            }
            case "work_info" -> activityFlag_wooden = "WORK";
            case "contact_info" -> {
                activityFlag_wooden = "CONTACT";
                titleView.setVisibility(VISIBLE);
                tipsView.setVisibility(VISIBLE);
                tipsTv.setText(getText(R.string.process_tips_contact));
            }
            case "account_info" -> activityFlag_wooden = "BVN";
            default -> activityFlag_wooden = buriedPointFalg_wooden;
        }

        if (step_wooden ==null) return;

        if (StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Cote_wooden) ||
                StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Vietnam_wooden)){
            titleView.setTitle_wooden(ProcessInfo_wooden.getInstance_wooden().getStepTitle_wooden());
        }else titleView.setTitle_wooden(StringUtil_wooden.processTitleFormat_wooden(ProcessInfo_wooden.getInstance_wooden().getStepName_wooden(0)));

        //联系人信息单独处理
        if (step_wooden.isContact_wooden()){

            for (int i = 0; i< step_wooden.getExtDataListSize_wooden(); i++){
                ProcessData_wooden data = step_wooden.getExtProcessData_wooden(i);
                if (data==null) continue;
                addInputView_wooden(data,null);
            }

            //添加分割线
            if (step_wooden.getExtDataListSize_wooden()>0) groupLayout_wooden.addView(LayoutInflater.from(this).inflate(R.layout.view_line_wooden,null));

            int count = 0;

            while (count< step_wooden.getItemCount_wooden()){//联系人数量

                View contactView = LayoutInflater.from(this).inflate(R.layout.view_contact,null);

                final int size = infoInputViewManagers_wooden.size();

                ContactViewManager_wooden contactViewManager_wooden =
                        new ContactViewManager_wooden(contactView,count+1,step_wooden.getRelationShips_wooden(count),
                                () -> {
                                    try {
                                        contactIndex = size;
                                        contactLauncher.launch(new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI));
                                    }catch (Exception e){
                                        if (Constant_wooden.Debug) e.printStackTrace();
                                    }
                                });

                infoInputViewManagers_wooden.add(contactViewManager_wooden);

                groupLayout_wooden.addView(contactView);

                //添加分割线
                if (++count < step_wooden.getItemCount_wooden()) groupLayout_wooden.addView(LayoutInflater.from(this).inflate(R.layout.view_line_wooden,null));

            }

            return;
        }

        for (int i = 0; i< step_wooden.getDataListSize_wooden(); i++){
            ProcessData_wooden data = step_wooden.getProcessData_wooden(i);
            if (data==null) continue;
            addInputView_wooden(data,null);
        }
    }

    //添加信息输入控件
    @SuppressLint("InflateParams")
    private void addInputView_wooden(ProcessData_wooden data, ArrayList<String> relationships){

        View inputView = null;

        switch (data.getAction_wooden()) {
            case Constant_wooden.Data_Action_Select_wooden -> {
                inputView = LayoutInflater.from(this).inflate(R.layout.view_select_wooden, null);
                SelectViewManager_wooden selectViewManager = new SelectViewManager_wooden(inputView, data,
                        buriedPointFalg_wooden+"_"+data.getParamName_wooden()+"_INPUT");
                infoInputViewManagers_wooden.add(selectViewManager);
            }
            case Constant_wooden.Data_Action_Date_Pick_wooden -> {
                inputView = LayoutInflater.from(this).inflate(R.layout.view_date_picker_wooden, null);
                DatePickViewManager_wooden datePickWidgetsManager = new DatePickViewManager_wooden(inputView, data,
                        buriedPointFalg_wooden+"_"+data.getParamName_wooden()+"_INPUT");
                infoInputViewManagers_wooden.add(datePickWidgetsManager);
            }
            case Constant_wooden.Data_Action_Relation_wooden -> {//联系人-关系
                if (relationships != null) data.setRelationships_wooden(relationships);
                inputView = LayoutInflater.from(this).inflate(R.layout.view_select_wooden, null);
                SelectViewManager_wooden contactSelectViewManager = new SelectViewManager_wooden(inputView, data,
                        buriedPointFalg_wooden+"_"+data.getParamName_wooden()+"_INPUT");
                infoInputViewManagers_wooden.add(contactSelectViewManager);
            }
            case Constant_wooden.Data_Action_Gender_Pick_wooden -> {
                inputView = LayoutInflater.from(this).inflate(R.layout.view_gender_select_wooden, null);
                GenderSelectViewManager_wooden genderSelectViewManager = new GenderSelectViewManager_wooden(inputView, data);
                infoInputViewManagers_wooden.add(genderSelectViewManager);
            }
            case Constant_wooden.Data_Action_Credit_Report_wooden -> {//尼日同意征信收集模块
                inputView = LayoutInflater.from(this).inflate(R.layout.view_credit_report_niri_wooden, null);
                CreditReportViewManager_Niri_wooden creditReportViewManager = new CreditReportViewManager_Niri_wooden(inputView, data);
                infoInputViewManagers_wooden.add(creditReportViewManager);
            }
            case Constant_wooden.Data_Action_Address_Pick_wooden -> {//地址联动模块
                //尼日
                if (StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Nigeria_wooden)) {
                    inputView = LayoutInflater.from(this).inflate(R.layout.view_address_pick_wooden, null);
                    AddressPickViewManager_Niri_wooden addressPickViewManager = new AddressPickViewManager_Niri_wooden(inputView, data);
                    infoInputViewManagers_wooden.add(addressPickViewManager);
                }
                //越南
                if (StaticVariate_wooden.Select_Country_wooden.equalsIgnoreCase(Constant_wooden.Country_Vietnam_wooden)) {
                    inputView = LayoutInflater.from(this).inflate(R.layout.view_address_pick_wooden, null);
                    AddressPickViewManager_Viet_wooden addressPickViewManager = new AddressPickViewManager_Viet_wooden(inputView, data);
                    infoInputViewManagers_wooden.add(addressPickViewManager);
                }
            }
            case Constant_wooden.Data_Action_Bank_Pick_wooden -> {//尼日银行选择模块
                bankNameData_wooden = data;
                HttpManager_wooden.getInstance_wooden().fetchBankCodes_Niri_wooden();
            }

            default -> {
                inputView = LayoutInflater.from(this).inflate(R.layout.view_input_wooden, null);
                InputViewManager_wooden inputWidgetsManager = new InputViewManager_wooden(inputView, data,
                        buriedPointFalg_wooden+"_"+data.getParamName_wooden()+"_INPUT");
                infoInputViewManagers_wooden.add(inputWidgetsManager);
            }
        }

        if (inputView!=null) groupLayout_wooden.addView(inputView);
    }

    @Override
    public void recordPageResumeEvent_wooden() {
        HttpManager_wooden.getInstance_wooden().saveUserBuriedPoint((buriedPointFalg_wooden + "_START").toUpperCase());
    }

    @Override
    public void recordPagePauseEvent_wooden(boolean isOverdue) {
        HttpManager_wooden.getInstance_wooden().saveUserBuriedPoint((buriedPointFalg_wooden + "_END").toUpperCase());
    }

}